<template>
  <div class="navbar">
    <el-row>
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-menu :default-active="routePath" class="el-menu-demo" router mode="horizontal" text-color="RGB(30,30,30)" active-text-color="RGB(64,158,255)">
          <img src="../../assets/img/logo.png" alt="error">
          <el-menu-item index="/MusicHall">音乐馆</el-menu-item>
          <el-menu-item index="/MyMusic">我的音乐</el-menu-item>
          <el-menu-item index="/Musician">不同凡响</el-menu-item>
          <el-menu-item index="/VIP">VIP</el-menu-item>
          <el-button plain @click="loginVisible = true" v-if="isLogin.btn">登录</el-button>

          <el-dropdown>
            <span class="el-dropdown-link">
              <el-avatar :src="userImgUrl" :key="userImgUrl" v-if="isLogin.img" :size="50" @click.native="toMyMusic"></el-avatar>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="toEditUserInfo">编辑资料</el-dropdown-item>
              <el-dropdown-item @click.native="exitLogin">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu>
        <el-autocomplete class="search-input" v-model="input" :fetch-suggestions="querySearch" placeholder="搜索音乐、歌手、歌单、MV" prefix-icon="el-icon-search" clearable @focus="hotList" @keydown.enter.native="searchMsg()" @select="handleSelect"></el-autocomplete>

        <el-dialog title="登录" :visible.sync="loginVisible" width="30%" center>
          <el-form :model="formLogin" status-icon :rules="rules" ref="formLogin">
            <el-form-item label="账号" prop="loginUser">
              <el-input type="text" v-model="formLogin.loginUser" placeholder="请输入账号" required></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="loginPass">
              <el-input type="password" v-model="formLogin.loginPass" placeholder="请输入密码" required></el-input>
            </el-form-item>
            <el-form-item>
              <span @click="regVisible = true">注册</span>
              <span class="forgetPass">忘记密码</span>
            </el-form-item>
          </el-form>
          <el-dialog width="30%" title="注册" :visible.sync="regVisible" append-to-body center>
            <el-form :model="formReg" status-icon :rules="rules" ref="formReg">
              <el-form-item label="账号" prop="user">
                <el-input type="text" v-model="formReg.user" placeholder="请输入账号" required></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="pass">
                <el-input type="password" v-model="formReg.pass" placeholder="请输入密码" required></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" v-model="formReg.checkPass" placeholder="请再次输入密码" required></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button plain @click="regSubmit">注册</el-button>
              <el-button plain @click="regVisible = false">取 消</el-button>
            </div>
          </el-dialog>
          <div slot="footer" class="dialog-footer">
            <el-button plain @click="loginSubmit">登录</el-button>
            <el-button plain @click="loginVisible = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>

      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <router-view></router-view>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { login, exitLogin, register, getUserInfo } from "../../network/user";
import { getHotList, loginDefaultUser } from "../../network/home";

export default {
  name: "NavBar",
  data() {
    var validateUser = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8|9][0-9]{9}$/;
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
        // 所以我就在前面加了一个+实现隐式转换
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式/长度不正确'))
          }
        }
      }, 100)
    }
    var validatePass = (rule, value, callback) => {
      const passReg = /^[a-zA-Z]\w{8,18}$/;
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (!passReg.test(value)) {
        callback();
      } else {
        if (this.formReg.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validateCheckPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.formReg.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      input: "",
      routePath: "",
      loginVisible: false,
      regVisible: false,
      formLogin: {
        loginUser: "",
        loginPass: "",
      },
      formReg: {
        user: "",
        pass: "",
        checkPass: "",
      },
      rules: {
        user: [
          { validator: validateUser, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validateCheckPass, trigger: 'blur' }
        ],
      },
      restaurants: [],
      hots: [],
      loginTime: "",
      isLogin: {},
      userImgUrl: "",
    };
  },
  created() {
    this.loginDefaultUser("18874070139", "yz520.");
    this.verLogin();
  },
  mounted() {
    //获取一级路径结尾的位置 /MusicHall/Page 结尾的位置为 10
    let index = this.$route.path.indexOf("/", 1);
    if (index != -1) {
      //截出一级路径
      this.routePath = this.$route.path.slice(0, index);
    } else {
      this.routePath = this.$route.path;
    }

    //如果在搜索界面 刷新页面 搜索框内容还在
    if (this.$route.path == "/Search") {
      this.input = sessionStorage.getItem("songTitle");
    }
    this.restaurants = this.hots;
  },
  methods: {
    searchMsg() {
      //如果当前页面不在搜索页面 那么跳转到搜索页面，将当前选中改为MusicHall并将输入框内容传入sessionStorage
      //如果不在 那么直接将输入框内容传入sessionStorage
      if (this.$route.path != "/Search") {
        this.$router.push("/Search");
        this.routePath = "/MusicHall";
        sessionStorage.setItem("songTitle", this.input);
      } else {
        sessionStorage.setItem("songTitle", this.input);
        //刷新页面 input传入过去 其中内容改了 但是页面还是原来的 需要刷新显示
        location.reload();
      }
    },
    verLogin() {
      if (localStorage.getItem("loginTime") == null) {
        this.isLogin = { btn: true, img: false };
      } else {
        this.isLogin = { btn: false, img: true };
        this.getUserInfo(localStorage.getItem("username"));
      }
    },
    loginSubmit() {
      login(this.formLogin.loginUser, this.formLogin.loginPass).then((res) => {
        console.log(res.data);
        if (res.data == "500") {
          alert("账号或密码不正确，请重新输入！");
        } else {
          this.loginTime = res.data.loginTime;
          localStorage.setItem("loginTime", this.loginTime);
          this.isLogin.btn = false;
          this.isLogin.img = true;
          localStorage.setItem("username", this.formLogin.loginUser);
          this.getUserInfo(this.formLogin.loginUser);
          //刷新页面 让登陆头像显示
          location.reload();
        }
      });
      this.loginVisible = false;
    },
    regSubmit() {
      if (this.formReg.pass === this.formReg.checkPass) {
        register(this.formReg.user, this.formReg.pass).then((res) => {
          console.log(res.data);
          this.regVisible = false;
        });
      } else {
        alert("两次密码不一样，请重新输入");
      }
    },
    exitLogin() {
      exitLogin(localStorage.getItem("username")).then(res => {
        if (res.data == "200") {
          this.isLogin.btn = true;
          this.isLogin.img = false;
          localStorage.removeItem("loginTime");
          localStorage.removeItem("username")
          //刷新页面 让登陆按钮重新显示
          location.reload();
          alert("退出成功！");
        }
      })
    },
    getUserInfo(username) {
      getUserInfo(username).then(res => {
        this.userImgUrl = res.data.virPath + "/" + res.data.userImgName;
      })
    },
    // toEditUserInfo() {
    //   getUserInfo(sessionStorage.getItem("username")).then(res => {
    //     this.$store.commit("getUserInfo", res.data);
    //   })
    //   this.$router.push("/UserInfo");
    // },
    toEditUserInfo() {
      this.$router.push("/UserInfo");
    },
    // toMyMusic() {
    //   this.routePath = this.$route.path;
    //   this.$router.push("/MyMusic");
    //   location.reload();
    // },
    hotList() {
      getHotList().then((res) => {
        //将返回结果作为对象循环遍历到hots数组中，为querySearch使用
        //console.log(res.data);
        for (var i = 0; i < res.data.result.hots.length; i++) {
          this.hots.push({ value: res.data.result.hots[i].first });
        }
      });
    },
    // fetch-suggestions	 返回输入建议的方法，仅当你的输入建议数据 resolve 时，通过调用 cb(data:[]) 来返回它
    querySearch(queryString, cb) {
      //queryString 为选中的建议项
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    // 点击选中建议项时触发handleSelect
    handleSelect() {
      //搜索该项，并跳转到search
      this.searchMsg();
    },
    /**
     * 默认登陆用户
     * 因为用网易云api有些功能不用网易云账号登陆就无法使用
     * 所以用网易云账号默认登陆
     * 具体需要登陆的功能再自己手动做拦截
     */
    loginDefaultUser(phone, password) {
      loginDefaultUser(phone, password).then(res => {
        sessionStorage.setItem("cookie", res.data.cookie);
      })
    },
  },
};
</script>

<style scoped>
.navbar {
  margin: 0px 100px 10px 100px;
  width: auto;
  height: auto;
}
.el-menu-demo {
  padding-left: 50px;
}
.el-menu-demo .el-menu-item {
  font-size: 1.25rem;
}
.el-menu-demo .el-menu-item:hover {
  color: RGB(64, 158, 255) !important;
}
.el-menu-demo img {
  height: 50px;
  width: 120px;
  float: left;
  margin-right: 20px;
}
@media screen and (min-device-width: 1200px) {
  .search-input {
    width: 22%;
    margin: -50px 0 20px 67%;
    border-color: RGB(54, 170, 101);
    display: block;
  }
  .el-menu-demo .el-button {
    margin-left: 91%;
    margin-top: 10px;
    display: block;
  }
  .el-menu-demo .el-dropdown {
    margin: 0 0 0 94.5%;
    display: block;
  }
}
@media screen and (max-device-width: 1200px) {
  .search-input {
    width: 10%;
    margin: -50px 0 20px 80%;
    border-color: RGB(54, 170, 101);
    display: block;
  }
  .el-menu-demo .el-button {
    margin-left: 91%;
    margin-top: 10px;
    display: block;
  }
  .el-menu-demo .el-dropdown {
    margin: 0 0 0 94.5%;
    display: block;
  }
}
.el-dialog .el-form .el-form-item {
  margin-left: 35px;
}
.el-dialog .el-form .el-form-item .el-input {
  width: 300px;
  border-color: RGB(54, 170, 101);
}
.forgetPass {
  margin-left: 255px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
